package com.sftz.modules.minapp.personal.service;

import java.util.List;
import java.util.Map;

import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.SqlManager;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Sql;
import org.nutz.ioc.aop.Aop;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.log.Log;
import org.nutz.log.Logs;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.sftz.assets.entities.InstitutionStudentFormStatusEntity;
import com.sftz.assets.entities.InstitutionStudentFormValueEntity;
import com.sftz.framework.constants.CommonConstants;
import com.sftz.modules.minapp.personal.dto.StudentFormInstDto;
import com.sftz.modules.minapp.personal.dto.StudentFormValueDto;
import com.uxuexi.core.common.util.DateTimeUtil;
import com.uxuexi.core.common.util.ExceptionUtil;
import com.uxuexi.core.common.util.Util;
import com.uxuexi.core.db.dao.IDbDao;
import com.uxuexi.core.db.util.DbSqlUtil;

@IocBean
public class StudentFormService {

	private static final Log log = Logs.get();

	/**
	 * 注入容器中的dbDao对象，用于数据库查询、持久操作 
	 */
	@Inject
	private IDbDao dbDao;

	/**nutz dao*/
	@Inject
	private Dao nutDao;

	/**
	 * 注入容器中的sqlManager对象，用于获取sql
	 */
	@Inject
	private SqlManager sqlManager;

	/**
	 * 查询用户机构表单填写状态
	 */
	public InstitutionStudentFormStatusEntity queryStatus(int userId, int institutionId) {
		List<InstitutionStudentFormStatusEntity> list = dbDao.query(InstitutionStudentFormStatusEntity.class, Cnd
				.where("userId", "=", userId).and("institutionId", "=", institutionId), null);
		if (!Util.isEmpty(list)) {
			if (list.size() > 1) {
				throw ExceptionUtil.bEx("表单填写数据有错误，请检查！机构id:" + institutionId + ",用户id:" + userId);
			} else {
				return list.get(0);
			}
		}
		return null;
	}

	/**
	 * 判断用户是否已经填写过机构表单
	 */
	public boolean isFilled(int userId, int institutionId) {
		InstitutionStudentFormStatusEntity en = queryStatus(userId, institutionId);
		if (Util.isEmpty(en)) {
			return false;
		} else {
			return true;
		}
	}

	/**
	 * 查询机构表单项
	 */
	public List<StudentFormValueDto> queryFormItems(int institutionId) {
		Sql sql = Sqls.create(sqlManager.get("minapp_studentform_queryItemInfo"));
		sql.params().set("institutionId", institutionId);
		List<StudentFormValueDto> itemList = DbSqlUtil.query(dbDao, StudentFormValueDto.class, sql, null);
		return itemList;
	}

	/**
	 * 查询用户机构表单
	 * <P>
	 * itemList 为该机构的所有表单项
	 * formValue 为所有表单值
	 */
	public Map<String, Object> queryFormInfo(int userId, int institutionId) {
		Map<String, Object> map = Maps.newHashMap();
		List<StudentFormValueDto> itemList = queryFormItems(institutionId);

		Sql sql = Sqls.create(sqlManager.get("minapp_studentform_queryformInfo"));
		sql.params().set("institutionId", institutionId);
		sql.params().set("userId", userId);

		List<StudentFormValueDto> formValue = DbSqlUtil.query(dbDao, StudentFormValueDto.class, sql, null);
		map.put("itemList", itemList);
		map.put("formValue", formValue);

		return map;
	}

	/**
	 * 根据课程id查询机构id, 查不到返回-1
	 */
	public int queryInstitutionId(int courseId) {
		Sql sql = Sqls.create(sqlManager.get("minapp_studentform_institutionIdbycourse"));
		sql.params().set("courseId", courseId);
		List<StudentFormInstDto> list = DbSqlUtil.query(dbDao, StudentFormInstDto.class, sql, null);
		if (!Util.isEmpty(list)) {
			return list.get(0).getInstitutionId();
		}
		return CommonConstants.NOT_EXIST_ID;
	}

	/**
	 * 保存用户表单信息
	 */
	@Aop("txDb")
	public boolean saveOrUpdate(List<InstitutionStudentFormValueEntity> toBeSave) {
		if (!Util.isEmpty(toBeSave)) {
			List<InstitutionStudentFormValueEntity> toAdd = Lists.newArrayList();
			for (InstitutionStudentFormValueEntity val : toBeSave) {
				InstitutionStudentFormValueEntity ov = dbDao.fetch(InstitutionStudentFormValueEntity.class,
						Cnd.where("userId", "=", val.getUserId()).and("itemId", "=", val.getItemId()));
				if (Util.isEmpty(ov)) {
					toAdd.add(val);
				} else {
					//更新
					dbDao.update(InstitutionStudentFormValueEntity.class, Chain.make("itemValue", val.getItemValue())
							.add("updateTime", DateTimeUtil.nowDateTime()), Cnd.where("id", "=", ov.getId()));
				}
			}
			if (!Util.isEmpty(toAdd)) {
				dbDao.insert(toAdd);
			}
		}
		return true;
	}
}
